package learnjava.basic.other;

import java.io.IOException;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;

public class TestPipeIO {

    public static void main(String[] args) throws Exception{

        PipedOutputStream pos = new PipedOutputStream();
        PipedInputStream pis = new PipedInputStream();
        pis.connect(pos);
        Thread reader = new Thread(new Read(pis));
        Thread writer = new Thread(new Write(pos));
        reader.start();
        writer.start();
    }
}

class Read implements Runnable{

    PipedInputStream pis;

    public Read(PipedInputStream pis) {
        this.pis = pis;
    }

    @Override
    public void run() {
        byte[] buffer = new byte[1024];
        int len = 0;
        try {
            len = pis.read(buffer);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String s = new String(buffer,0,len);
        System.out.println(s);
    }
}

class Write implements Runnable{

    PipedOutputStream pos;

    public Write(PipedOutputStream pos) {
        this.pos = pos;
    }

    @Override
    public void run() {
        try {
            pos.write("welcomeMe...".getBytes());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
